import {
  Box,
  Card,
  CardContent,
  CardMedia,
  IconButton,
  LinearProgress,
  Typography,
  Zoom,
} from "@mui/material"
import SaveIcon from "@mui/icons-material/Save"
import React, { useEffect, useRef, useState } from "react"
import PauseCircleIcon from "@mui/icons-material/PauseCircle"
import PlayCircleIcon from "@mui/icons-material/PlayCircle"
import { useTheme } from "@mui/material/styles"
import MusicVideoIcon from "@mui/icons-material/MusicVideo"
import PlaylistAddIcon from "@mui/icons-material/PlaylistAdd"
import { useRequest } from "ahooks"
import { song } from "@/services/kugou"
import { message } from "antd"
import { LoadingOutlined } from "@ant-design/icons"
import { Dialog } from "antd-mobile"
import { uploadRemote } from "@/services"

export type MusicCardModel = "mini"
export interface MusicCardInfo {
  value?: any
  mocel?: MusicCardModel
  onToggle?: (info: any) => void
  hash?: string
  canPlay?: boolean //当前卡片是否可以播放（同时只有一个卡片可以播放）
}
export default (props: MusicCardInfo) => {
  const { value, onToggle, canPlay = true, hash, ...otr } = props
  const theme = useTheme()
  const AUDIO = useRef<HTMLAudioElement>(null)
  const [playProcess, setPlayProcess] = useState(0)
  const [running, setRunning] = useState(false)
  const [ended, setEnded] = useState(true)
  const [loading, setLoading] = useState(0)
  const [playInfo, setPlayInfo] = useState<{ url: string[] }>()
  const { runAsync } = useRequest((hash) => song(hash), {
    manual: true,
    onSuccess(data, params) {
      const res = data?.data
      if (res.status === 2) {
        message.error("【2】获取资源失败！")
      }
      if (res.status === 1) {
        setPlayInfo(res)
      }
    },
    onError(e, params) {
      message.error(e.message)
    },
  })
  const { runAsync: runSave, loading: saveLoading } = useRequest(
    (params) => uploadRemote(params),
    {
      manual: true,
    },
  )
  const saveHandler = async (record: any) => {
    try {
      const res = await runSave({
        name: record?.SongName,
        hash: record?.SQFileHash,
      })
      if (res?.status !== 200) {
        message.info(res?.data?.msg)
      } else {
        message.success("添加成功")
      }
    } catch (e) {
      /* empty */
    }
  }
  const handlePlay = async () => {
    if (!playInfo) {
      setLoading(1)
      await runAsync(value?.HQFileHash)
      setLoading(0)
      setTimeout(() => {
        running ? AUDIO.current?.pause() : AUDIO.current?.play()
      }, 0)
    } else {
      running ? AUDIO.current?.pause() : AUDIO.current?.play()
      onToggle?.(value)
      setRunning(!running)
    }
  }
  useEffect(() => {
    !canPlay && AUDIO.current?.pause()
  }, [canPlay])
  return (
    <>
      <Zoom in>
        <Card sx={{ width: "100%" }}>
          {playInfo ? (
            <audio
              onPlay={() => {
                setRunning(true)
                setEnded(false)
              }}
              onPause={() => {
                setRunning(false)
              }}
              onEnded={() => {
                setEnded(true)
                setPlayProcess(0)
              }}
              onError={() => {
                setRunning(false)
              }}
              onTimeUpdate={() => {
                if (AUDIO.current) {
                  const percent =
                    (AUDIO.current.currentTime / AUDIO.current.duration) * 100
                  setPlayProcess(parseFloat(percent.toFixed(1)))
                }
              }}
              ref={AUDIO}
              src={playInfo.url?.[0]}
            ></audio>
          ) : null}
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
            }}
          >
            <Box sx={{ display: "flex", flexDirection: "column" }}>
              <CardContent sx={{ flex: "1 0 auto" }}>
                <Typography component="div">{value?.SongName}</Typography>
                <Typography
                  variant="subtitle1"
                  component="div"
                  sx={{ color: "text.secondary" }}
                >
                  {value?.SingerName}
                </Typography>
              </CardContent>
              <Box sx={{ display: "flex", alignItems: "center", pl: 1, pb: 1 }}>
                <IconButton
                  aria-label="play/pause"
                  onClick={() => {
                    handlePlay()
                    // running ? AUDIO.current?.pause() : AUDIO.current?.play()
                    // onToggle?.(value)
                    // setRunning(!running)
                  }}
                >
                  {loading ? (
                    <LoadingOutlined />
                  ) : running ? (
                    <PauseCircleIcon></PauseCircleIcon>
                  ) : (
                    <PlayCircleIcon />
                  )}
                </IconButton>

                <IconButton aria-label="next">
                  <MusicVideoIcon></MusicVideoIcon>
                </IconButton>
                <IconButton
                  onClick={() => {
                    Dialog.show({
                      content: "是否将歌曲加入歌单?",
                      closeOnAction: true,
                      actions: [
                        [
                          {
                            key: "cancel",
                            text: "取消",
                            danger: true,
                          },
                          {
                            key: "ok",
                            text: "保存至歌单",
                          },
                        ],
                      ],
                      onAction: (action) => {
                        if (action.key == "ok") {
                          saveHandler(value)
                        }
                      },
                    })
                  }}
                  aria-label="previous"
                >
                  {saveLoading ? (
                    <LoadingOutlined />
                  ) : (
                    <PlaylistAddIcon></PlaylistAddIcon>
                  )}
                </IconButton>
              </Box>
            </Box>
            <CardMedia
              component="img"
              sx={{ width: 151 }}
              image={value?.cover}
              alt="封面加载失败"
            />
          </Box>
          {!ended ? (
            <LinearProgress variant="determinate" value={playProcess} />
          ) : null}
        </Card>
      </Zoom>
    </>
  )
}
